package com.authine.cloudpivot.ext.controller;

import com.authine.cloudpivot.engine.domain.runtime.BizWorkitem;
import com.authine.cloudpivot.engine.service.runtime.ExtProcessTaskServcie;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 任务创建扩展
 */
@Slf4j
@Service
public class ExampleProcessTaskServcieImpl implements ExtProcessTaskServcie {
    @Autowired
    CloudSqlService sqlService;

    /**
     * 获取到任务的流程名称和任务节点名称,拼接后修改 任务流程名称
     *
     * @param bizWorkitem
     * @return
     */
    @Override
    public BizWorkitem createProcessTaskEvent(final BizWorkitem bizWorkitem) {

        updateWorkItemInstanceName(bizWorkitem, "biz_workitem");

        return bizWorkitem;
    }

    private void updateWorkItemInstanceName(final BizWorkitem bizWorkitem, String tableName) {
        String instanceName = bizWorkitem.getInstanceName();
        String activityName = bizWorkitem.getActivityName();
        String id = bizWorkitem.getId();

        String activityNameSplicing = new StringBuilder("（").append(activityName).append("）").toString();
        //判断当前的instanceName是否已经包含节点名称，如果已经包含则不追加。（防止同一节点审批人转办，导致标题后出现多个相同节点名称的情况）
        if (!instanceName.contains(activityNameSplicing)) {
            log.info("instanceName:{}，在标题后追加节点名称", instanceName, activityName);
            instanceName = new StringBuilder(instanceName).append(activityNameSplicing).toString();
        }

        bizWorkitem.setInstanceName(instanceName);
        log.info("流程任务标题修改:{}", instanceName);

        StringBuilder sql = new StringBuilder(" update ").append(tableName).append(" set instanceName='").append(instanceName).append("' where instanceId='")
                .append(bizWorkitem.getInstanceId()).append("' and id = '").append(id).append("';");
        sqlService.update(sql.toString());
            log.info("执行更新待办流程名称SQL：{}", sql.toString());

        //如果tableName=biz_workitem_finished，那么已办表里考虑并行节点的情况，更新的instanceName值应该是（当前节点）（当前节点）

    }

    /**
     * 任务完成时调用，把任务从待办移到已办
     *
     * @param bizWorkitem
     */
    @Override
    public void completedProcessTaskEvent(final BizWorkitem bizWorkitem) {
        updateWorkItemInstanceName(bizWorkitem, "biz_workitem_finished");
    }
}
